<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>修改密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form :model="userPW" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="原密码" prop="old_pwd">
                        <el-input type="password" v-model="userPW.old_pwd" show-password/>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_pwd">
                        <el-input type="password" v-model="userPW.new_pwd" show-password/>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="re_pwd">
                        <el-input type="password" v-model="userPW.re_pwd" show-password/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updateUserPassword">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>
<script setup>
    import { ref} from 'vue'
    import { userResetPasswordService } from '@/api/user'
    import { ElMessage } from 'element-plus'

    const userPW = ref({
        old_pwd: '',
        new_pwd: '',
        re_pwd: '',
    })

    const updateUserPassword = async () => {
        const { old_pwd, new_pwd, re_pwd } = userPW.value
        if (new_pwd !== re_pwd) {
            return ElMessage.error('两次输入的密码不一致')
        }
        const res = await userResetPasswordService({
            old_pwd,
            new_pwd,
            re_pwd
        })
        // 删除本地原密码
        localStorage.removeItem('password')

        ElMessage.success(res.msg ? res.msg : '修改成功')  
    }

    const rules = {
        old_pwd: [
            { required: true, message: '请输入原始密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度为6~16位非空字符', trigger: 'blur' }
        ],
        new_pwd: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度为6~16位非空字符', trigger: 'blur' }
        ],
        re_pwd: [
           { required: true, message: '请输入确认密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度为6~16位非空字符', trigger: 'blur' }
        ]
    }
</script>